<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/07/20
 * Time: 11:08
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

class ProductKeywordCategory extends BaseModel
{
    protected $pk = 'cate_id';

    /**
     * 关联父分类
     * @return \think\model\relation\BelongsTo
     * @date 2021/07/20
     * @author longli
     */
    public function parent()
    {
        return $this->belongsTo(ProductCategory::class, 'parent_id', 'cate_id');
    }

    /**
     * 关联关键词
     * @return \think\model\relation\HasMany
     * @date 2021/07/20
     * @author longli
     */
    public function words()
    {
        return $this->hasMany(ProductKeyword::class, 'cate_id', 'cate_id');
    }

    /**
     * 获取当前分类下的所有子类
     * @param int $pid 父类 id
     * @return int[]
     * @date 2020/09/13
     * @author longli
     */
    public static function getAllSon($pid = 0)
    {
        $ids = [];
        if($pid > 0) $ids[] = $pid;
        do
        {
            $cates = static::where("parent_id", "in", $pid)->field("cate_id")->select()->toArray();
            if(!empty($cates))
            {
                $pid = array_column($cates, 'cate_id');
                $ids = array_merge($pid, $ids);
            }
        }while(!empty($cates));
        return static::where("cate_id", "in", $ids)->column('cate_id');
    }

    /**
     * 获取所有关键词分类，并生成树形结构数据
     * @return array
     * @date 2021/07/20
     * @author longli
     */
    public static function getAllByTree()
    {
        $cates = static::where("status", self::IS_YES)->select()->toArray();
        $cates = \app\common\library\Tools::generateTree($cates, 'cate_id', 'parent_id');
        $cates = \app\common\library\Tools::levelArray($cates);
        return $cates;
    }

    /**
     * 分类名称是否存在
     * @param string $name 分类名称
     * @return bool
     * @date 2021/07/21
     * @author longli
     */
    public static function hasName($name)
    {
        return !!static::where("name", trim($name))->count();
    }

    /**
     * 检查面包屑名称是否存在
     * @param string $names 分类面包屑名称
     * @param int $lastId 最后一个分类id
     * @return bool
     * @date 2021/07/21
     * @author longli
     * @example name1>name2
     */
    public static function hasMoreName($names, &$lastId = null)
    {
        $pid = null;
        foreach(explode('>', $names) as $name)
        {
            $where = [["name", "eq", trim($name)]];
            if(!empty($pid)) $where[] = ["parent_id", "eq", $pid];
            if(!($cate = static::where($where)->find()))
            {
                $lastId = 0;
                return false;
            }
            $lastId = $pid = $cate->cate_id;
        }
        return true;
    }
}
